package com.rong.raft.rpc.net;

import java.rmi.Naming;
import java.rmi.Remote;
import java.util.concurrent.atomic.AtomicBoolean;

import com.rong.raft.rpc.IRpcService;

/**
 * 
 * @desc rpc服务客户端
 *
 * @author liurong
 *
 * @date 2019年10月22日
 */
public class RpcClient extends Thread {

	private String address;
	private IRpcService rpcService;
	private AtomicBoolean isStart = new AtomicBoolean(false);

	private int rateLimit = 0;

	public RpcClient(String address) {
		this.address = address;
	}

	public IRpcService getRpcService() {
		return rpcService;
	}

	public boolean getIsStart() {
		return isStart.get();
	}

	@Override
	public void run() {
		while (!isStart.get()) {
			try {
				Remote lookup = Naming.lookup("rmi://" + address + "/rpc");
				if (lookup instanceof IRpcService) {
					rpcService = (IRpcService) lookup;
				}
				isStart.compareAndSet(false, true);

				System.out.println("rpc consumer start success! address=" + address);

			} catch (Exception e) {
				if (rateLimit++ % 100 == 0) {
					System.out.println("服务端还没有启动，睡一下重连！" + address);
				}
				try {
					sleep(10);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

}
